package com.cssw.fyzb.web.util;



import com.cssw.fyzb.core.model.dodb.SysFunc;
import com.cssw.fyzb.web.vo.FuncTreeVo;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class FuncUtil {

    public static List<FuncTreeVo> getTree(List<SysFunc> funcs) {
        if (null == funcs || funcs.isEmpty()) {
            return null;
        }
        List<FuncTreeVo> funcTreeVos = new ArrayList<>();
        FuncTreeVo funcTreeVo = null;
        for (SysFunc func : funcs) {
            funcTreeVo = new FuncTreeVo();
            funcTreeVo.setFuncId(func.getFuncId());
            funcTreeVo.setSupFuncId(func.getSupFuncId());
            funcTreeVo.setFuncIcon(func.getFuncIcon());
            funcTreeVo.setFuncCode(func.getFuncCode());
            funcTreeVo.setFuncUrl(func.getFuncUrl());
            funcTreeVo.setFuncName(func.getFuncName());
            funcTreeVo.setFuncType(func.getFuncType());
            funcTreeVo.setSort(func.getSort());
            funcTreeVos.add(funcTreeVo);
        }
        funcTreeVos.sort(Comparator.comparing(FuncTreeVo::getSort, Comparator.nullsLast(Integer::compareTo)));
        List<FuncTreeVo> treeList = build(funcTreeVos, "0");

        return treeList;
    }

    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    private static List<FuncTreeVo> build(List<FuncTreeVo> treeNodes, String root) {

        List<FuncTreeVo> trees = new ArrayList<>();

        for (FuncTreeVo treeNode : treeNodes) {
            if (root.equals(treeNode.getSupFuncId().toString())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }


    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    private static FuncTreeVo findChildren(FuncTreeVo treeNode, List<FuncTreeVo> treeNodes) {
        for (FuncTreeVo it : treeNodes) {
            if (StrUtil.equals(treeNode.getFuncId().toString(), it.getSupFuncId().toString())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}

